import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/udt_tb_docmentstock_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/udt_tb_docmentstock.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/udt_tb_docmentstock_edit.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock_search/udt_tb_docmentstock_search_dialog.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/utils/utils.dart';

class UdtTbDocmentstockSearchList extends StatefulWidget {
  UdtTbDocmentstockSearchList({Key? key}) : super(key: key);

  @override
  _UdtTbDocmentstockListSearchState createState() =>
      _UdtTbDocmentstockListSearchState();
}

class _UdtTbDocmentstockListSearchState
    extends State<UdtTbDocmentstockSearchList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'id', asc: false)]);
  UdtTbDocmentstock udtTbDocmentstock = UdtTbDocmentstock();
  List<UdtTbDocmentstock> selectedList = [];
  //部门
  late List<SelectOptionVO> departmentList = [];
  //文档类别
  late List<SelectOptionVO> docmenttypeList = [];

  @override
  void initState() {
    var deparment =
        StoreUtil.read(Constant.KEY_CURRENT_USER_INFO)[0]["department_id"];
    udtTbDocmentstock.departmentId = deparment[0].toString();
    _loadSelectVO();
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  _loadSelectVO() async {
    departmentList = await DynamicDataApi.getModelSelect(
        model: "hr.department", name: "complete_name");
    docmenttypeList = await DynamicDataApi.getModelSelect(
        active: false,
        model: "dms.documenttype",
        name: "documenttypename",
        key: "department_id",
        val: int.parse(udtTbDocmentstock.departmentId!));
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelect(
            width: 280,
            label: '所属部门',
            dataList: departmentList,
            value: udtTbDocmentstock.departmentId,
            onSaved: (v) => {udtTbDocmentstock.departmentId = v},
            onChange: (v) async {
              if (udtTbDocmentstock.departmentId != v) {
                formKey.currentState!.save();
                udtTbDocmentstock.departmentId = v;
                udtTbDocmentstock.documenttypeId = null;
                try {
                  docmenttypeList = await DynamicDataApi.getModelSelect(
                      active: false,
                      model: "dms.documenttype",
                      name: "documenttypename",
                      key: "department_id",
                      val: int.parse(v));
                } catch (e) {
                  docmenttypeList = [];
                }
                setState(() {});
              }
            },
          ),
          CrySelect(
            width: 280,
            label: '档案项目',
            dataList: docmenttypeList,
            value: udtTbDocmentstock.documenttypeId,
            onSaved: (v) => {udtTbDocmentstock.documenttypeId = v},
          ),
          CryInput(
            width: 140,
            label: '附件名称',
            value: udtTbDocmentstock.fileName,
            onSaved: (v) {
              udtTbDocmentstock.fileName = v;
            },
          ),
          CryInput(
            width: 160,
            label: '档案盒名称',
            value: udtTbDocmentstock.documentname,
            onSaved: (v) {
              udtTbDocmentstock.documentname = v;
            },
          ),
          CryInput(
            width: 140,
            label: '备注',
            value: udtTbDocmentstock.remark,
            onSaved: (v) {
              udtTbDocmentstock.remark = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('档案盒状态')),
        DataColumn(label: Text('档案盒编号')),
        DataColumn(label: Text('档案盒名称')),
        DataColumn(label: Text('所属部门')),
        DataColumn(label: Text('档案项目')),
        DataColumn(label: Text('备注')),
        DataColumn(label: Text('存放区域')),
        DataColumn(label: Text('存放位置')),
        DataColumn(label: Text('创建人')),
        DataColumn(label: Text('创建时间')),
      ],
      getCells: (m) {
        UdtTbDocmentstock udtTbDocmentstock = UdtTbDocmentstock.fromMap(m);
        var flag = udtTbDocmentstock.remark!.contains("\n");
        var remark;
        if (flag) {
          remark = udtTbDocmentstock.remark!.split("\n")[0] + "...";
        } else {
          remark = udtTbDocmentstock.remark;
        }
        return [
          DataCell(Text(udtTbDocmentstock.status != null
              ? udtTbDocmentstock.status == '0'
                  ? '入库'
                  : '借出'
              : '--')),
          DataCell(Text(udtTbDocmentstock.documentno ?? '--')),
          DataCell(Text(udtTbDocmentstock.documentname ?? '--')),
          DataCell(Text(udtTbDocmentstock.departmentName ?? '--')),
          DataCell(Text(udtTbDocmentstock.documenttypeName ?? '--')),
          DataCell(Text(remark),
              onTap: flag ? () => _openDialog(udtTbDocmentstock.remark) : null),
          DataCell(Text(udtTbDocmentstock.areaName ?? '--')),
          DataCell(Text(udtTbDocmentstock.locationName ?? '--')),
          DataCell(Text(udtTbDocmentstock.createName ?? '--')),
          DataCell(Text(Utils.timeUTC(udtTbDocmentstock.createDate) ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _reset() async {
    udtTbDocmentstock = UdtTbDocmentstock();
    var deparment =
        StoreUtil.read(Constant.KEY_CURRENT_USER_INFO)[0]["department_id"];
    udtTbDocmentstock.departmentId = deparment[0].toString();
    docmenttypeList = await DynamicDataApi.getModelSelect(
        active: false,
        model: "dms.documenttype",
        name: "documenttypename",
        key: "department_id",
        val: int.parse(udtTbDocmentstock.departmentId!));
    formKey.currentState!.reset();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi =
        await UdtTbDocmentstockOdooApi.filePageSearch(data: {
      "page": page,
      "domainList": udtTbDocmentstock.toDomainList()
    });

    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _openDialog(String? remark) {
    Size size = boundingTextSize(remark!);
    showDialog(
        context: context,
        builder: (BuildContext context) => Dialog(
                child: SizedBox(
              width: size.width,
              height: size.height + 120 < 600 ? size.height + 120 : 600,
              child: Scaffold(
                appBar: AppBar(
                  title: Text("备注详情"),
                ),
                body: SingleChildScrollView(
                  child: Padding(
                    padding: EdgeInsets.all(10),
                    child: Text(remark),
                  ),
                ),
              ),
            ))).then((v) {});
  }

  static Size boundingTextSize(String text,
      {int maxLines = 2 ^ 31, double maxWidth = double.infinity}) {
    if (text == null || text.isEmpty) {
      return Size.zero;
    }
    final TextPainter textPainter = TextPainter(
        textDirection: TextDirection.ltr,
        text: TextSpan(text: text),
        maxLines: maxLines)
      ..layout(maxWidth: maxWidth);
    return textPainter.size;
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: UdtTbDocmentstockSearchDialog(),
      ),
    ).then((v) {
      if (v != null) {
        udtTbDocmentstock = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<UdtTbDocmentstock>((e) => UdtTbDocmentstock.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
      ],
    );
  }
}
